package com.example.computer_exam_training_sys.mapper;

import com.example.computer_exam_training_sys.entity.UserStudyReminder;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface UserStudyReminderMapper {
    
    @Results(id = "reminderMap", value = {
        @Result(property = "reminderId", column = "reminder_id"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "reminderType", column = "reminder_type"),
        @Result(property = "reminderTime", column = "reminder_time"),
        @Result(property = "reminderDays", column = "reminder_days"),
        @Result(property = "isActive", column = "is_active"),
        @Result(property = "createTime", column = "create_time"),
        @Result(property = "updateTime", column = "update_time"),
        @Result(property = "userName", column = "username")
    })
    @Select("SELECT r.*, u.username FROM user_study_reminders r " +
            "INNER JOIN users u ON r.user_id = u.user_id " +
            "WHERE r.user_id = #{userId}")
    List<UserStudyReminder> findByUserId(@Param("userId") Long userId);
    
    @ResultMap("reminderMap")
    @Select("SELECT r.*, u.username FROM user_study_reminders r " +
            "INNER JOIN users u ON r.user_id = u.user_id " +
            "WHERE r.reminder_id = #{reminderId}")
    UserStudyReminder findById(@Param("reminderId") Long reminderId);
    
    @Insert("INSERT INTO user_study_reminders (user_id, reminder_type, reminder_time, " +
            "reminder_days, is_active, create_time, update_time) " +
            "VALUES (#{userId}, #{reminderType}, #{reminderTime}, " +
            "#{reminderDays}, #{isActive}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "reminderId")
    void insert(UserStudyReminder reminder);
    
    @Update("UPDATE user_study_reminders SET is_active = #{isActive}, " +
            "update_time = NOW() WHERE reminder_id = #{reminderId}")
    void updateStatus(@Param("reminderId") Long reminderId, @Param("isActive") Boolean isActive);
    
    @Select("SELECT r.*, u.username FROM user_study_reminders r " +
            "INNER JOIN users u ON r.user_id = u.user_id " +
            "WHERE r.is_active = true " +
            "AND r.reminder_time <= #{currentTime}")
    List<UserStudyReminder> findPendingReminders(@Param("currentTime") LocalDateTime currentTime);

    @ResultMap("reminderMap")
    @Select("SELECT r.*, u.username FROM user_study_reminders r " +
            "INNER JOIN users u ON r.user_id = u.user_id " +
            "WHERE r.user_id = #{userId} " +
            "AND r.is_active = true " +
            "AND r.reminder_time <= #{currentTime}")
    List<UserStudyReminder> findTriggeredReminders(@Param("userId") Long userId, @Param("currentTime") LocalDateTime currentTime);
} 